<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>文章列表</title>

	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
	<link rel="stylesheet" href="../../static/css/font.css">
	<link rel="stylesheet" href="../../static/css/weadmin.css">
	<!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
	<!--[if lt IE 9]>
	<script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
	<script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
	<![endif]-->
	<style type="text/css">
		.layui-form-switch {
			width: 55px;
		}
		.layui-form-switch em {
			width: 40px;
		}
		body{overflow-y: scroll;}
	</style>
</head>

<body>
<div class="weadmin-nav">
         <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a href="">通知管理</a>
        <a>
          <cite>通知列表</cite></a>
      </span>
	<a class="layui-btn layui-btn-sm" style="line-height:1.6em;margin-top:3px;float:right" href="javascript:location.replace(location.href);" title="刷新">
		<i class="layui-icon" style="line-height:30px">&#x1002;</i></a>
</div>
<div class="weadmin-body">
	<div class="layui-row">
		<form class="layui-form layui-col-md12 we-search">
			通知搜索：
			<div class="layui-input-inline">
				<select id="notice-type-select" >
					<option value="">请选择分类</option>
				</select>
			</div>
			<div class="layui-input-inline">
				<select id="notice-status-select" >
					<option value="">请选择分类</option>
					<option value="1" >已审核通过</option>
					<option value="0"selected>审核不通过/未审核</option>
				</select>
			</div>
			<div class="layui-inline">
				<input class="layui-input" placeholder="开始日" name="start" id="startDate">
			</div>
			<div class="layui-inline">
				<input class="layui-input" placeholder="截止日" name="end" id="endDate">
			</div>

			<div id="search-notice" class="layui-btn"><span class="layui-icon layui-icon-search"></span>搜索</div>
			<div id="reset-notice" class="layui-btn layui-btn-primary"><span class="layui-icon layui-icon-refresh-1"></span>重置</div>
		</form>
	</div>
	<div class="weadmin-block demoTable">
		<button class="layui-btn layui-btn-danger" id="deleteNotices"><i class="layui-icon">&#xe640;</i>批量删除</button>

		<button class="layui-btn layui-btn-danger"  id="update-batch-refuse" ><i class="layui-icon layui-icon-close"></i>批量不通过</button>
		<button class="layui-btn"  id="update-batch-pass"><i class="layui-icon layui-icon-auz"></i>批量通过</button>


	</div>


	<div>
		<table class="layui-table" id="layui_table_id" lay-filter="dataTable"></table>
	</div>


	<script src="/assets/js/jquery.min.js" charset="utf-8"></script>
	<script src="../../lib/layui/layui.js" charset="utf-8"></script>

	<!--<script src="../../lib/layui/lay/modules/laydate.js"></script>-->
	<script type="text/javascript">

        $(function () {
            var webPath = "/big1";

			var userInfo = JSON.parse(sessionStorage.getItem("userInfo")) ;
			var schoolInfo = JSON.parse(sessionStorage.getItem("schoolInfo")) ;
			var superAdmin = userInfo.minLevel < 1 ;
			var schoolId = '';
			var schoolName = '';
			if ( !superAdmin ){//不是超级管理员
				schoolId = schoolInfo.id;
				schoolName = schoolInfo.schoolName;
			}

            initData();
            initDate();
            getNoticeTypes();
            function initDate() {
                layui.use('laydate', function(){
                    var laydate = layui.laydate;
                    var nowTime=new Date();
                    var startTime=laydate.render({
                        elem:'#startDate',
                        type:'datetime',
                        btns: ['confirm'],
                        //min:'nowTime',//默认最大值为当前日期
                        done:function(value,date){
                            endTime.config.min={
                                year:date.year,
                                month:date.month-1,//关键
                                date:date.date,
                                hours:date.hours,
                                minutes:date.minutes,
                                seconds:date.seconds
                            };

                        }
                    })
                    var endTime=laydate.render({
                        elem:'#endDate',
                        type:'datetime',
                        btns: ['confirm'],
                        /*max:'nowTime',*/
                        done:function(value,date){
                            startTime.config.max={
                                year:date.year,
                                month:date.month-1,//关键
                                date:date.date,
                                hours:date.hours,
                                minutes:date.minutes,
                                seconds:date.seconds
                            }

                        }
                    })

                });

            }

            $("#search-notice").click(function () {
                initData();
            });

            $("#reset-notice").click(function () {

				layui.use('form', function(){
					var form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
					//但是，如果你的HTML是动态生成的，自动渲染就会失效
					//因此你需要在相应的地方，执行下述方法来手动渲染，跟这类似的还有 element.init();
					$("#notice-type-select").val("")  ;
					$("#notice-status-select").val("")  ;
					$("#startDate").val("")  ;
					$("#endDate").val("")  ;
					form.render();
				});

				initData();

            });


            $("#update-batch-refuse").click(function () {
                updateStatusBatch("5");// 0未审核 1审核通过 2 过期 3草稿 4删除 5审核不通过
            });

            $("#update-batch-pass").click(function () {
                updateStatusBatch("1");// 0未审核 1审核通过 2 过期 3草稿 4删除 5审核不通过
            });

            function updateStatusBatch(status) {

                layui.use([ 'table','layer'] , function (){
                    var table = layui.table;
                    var layer = layui.layer;

                    var checkStatus = table.checkStatus('dataTable');
                    var data = checkStatus.data;
                    if (data.length < 1) {
                        layer.msg("请选择要操作的数据");
                        return;
                    }
                    var ids = [];
                    $.each(data,function (index,ele) {
                        ids.push(ele.id);
                    })
                    var obj = {noticeIds:ids,status:status};// 0未审核 1审核通过 2 过期 3草稿 4删除 5审核不通过

                    console.info(obj);

                    $.ajax({
                        url: webPath+"/notice/updateStatusBatch",
                        type: "POST",
                        data:JSON.stringify(obj),
                        contentType: 'application/json;charset=utf-8',
                        success: function(data) {
                            if (data.errorCode == "0") {
                                layer.msg("修改成功");
                                setTimeout(function () {initData();},300);
                            }else layer.msg("修改失败 "+JSON.stringify(data))

                        },
                        error: function(xhr, type, errorThrown) {
                            layer.msg("失败  "+JSON.stringify(xhr.responseJSON)  + "  "+JSON.stringify(errorThrown))
                        }
                    })//ajax

                })

            }

            function initData() {
                layui.use(['form', 'table','layer'] , function () {  // 引入 table模块
                    var table1 = layui.table;
                    var form = layui.form;
                    var layer = layui.layer;
                    table1.render({
                        id:"dataTable",//
                        elem: '#layui_table_id',//指定表格元素
                        url: webPath+'/adminNotice/getNoticeByMap',  //请求路径
                        contentType: 'application/json',
                        cellMinWidth: 20 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                        ,skin: 'line ' //表格风格 line （行边框风格）row （列边框风格）nob （无边框风格）
                        ,even: true    //隔行换色
                        ,page: true  //开启分页
                        ,limits: [5,10,20]  //每页条数的选择项，默认： 。
                        ,limit: 5 //每页默认显示的数量
                        ,method:'post'  //提交方式
                        ,where: {
                            /*currentPage: 1,
                            pageSize: 5,*/
                            typeId:$("#notice-type-select option:selected").val(),
							status:$("#notice-status-select option:selected").val(),
                            startDate:$("#startDate").val(),
                            endDate:$("#endDate").val(),
							schoolId:schoolId
                        }
                        ,request: {//用于对分页请求的参数：page、limit重新设定名称，如：
                            pageName: 'currentPage' //页码的参数名称，默认：page
                            ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
                        }
                        ,parseData: function(res){ //res 即为原始返回的数据
                            return {
                                "code": res.errorCode, //解析接口状态
                                "count": res.body.totalRecord, //解析数据长度
                                "data": res.body.list //解析数据列表
                            };
                        }
                        ,cols: [[
                            {type:'checkbox'}, //开启多选框
                            {
                                field: 'title',
                                title: '标题',
                                sort: true   // 默认为 false,true为开启排序
                            },
                            {
                                field: 'content',
                                title: '内容',

                            },
							{
								field: 'publisher',
								title: '发布者',
							},
                            {
                                field: 'startDate',
                                title: '开始时间',
                                sort: true
                            },
                            {
                                field: 'endDate',
                                title: '结束时间',
                            },
                            {
                                field: 'status',
                                title: '审核状态',
                                templet:function (d) {// 0未审核 1审核通过 2 过期 3草稿 4删除 5审核不通过
                                    var status = d.status ;
                                    var  check_btn = true;
                                    var  str = '';
                                    if (status == '1') str = '<input type="checkbox" id="'+d.id+'" value="'+d.status+'" lay-filter="switch"  lay-skin="switch" lay-text="通过|不通过" checked  >';
                                    else  str = '<input type="checkbox" id="'+d.id+'" value="'+d.status+'" lay-filter="switch" lay-skin="switch" lay-text="通过|不通过" />' ;
                                    return str;
                                }
                            },
                           /* {
                                field: 'id',
                                title: '操作',   //列名
                                templet:function (d) {//&#xe642;  &#xe63c; &#xe640;
                                    return "";
									var a  = '<div  class=""><span title="编辑" class="layui-icon layui-icon-edit" style="margin-left: 12px"></span>' +
                                        '<span title="删除"  class="layui-icon layui-icon-delete" style="margin-left: 12px"> </span></div>' ;
                                }
                            },*/
                        ]]
                        ,done: function(res, curr, count) {

                            form.on('switch(switch)', function(data){// 0未审核 1审核通过 2 过期 3草稿 4删除 5审核不通过
                                var j = $(data.elem);
                                var newCheck = data.elem.checked;
                                var status = '0';
                                if (newCheck == true ) status = '1'; //审核通过

                                var obj = {noticeId:$(data.elem).attr("id"),status:status};

                                $.ajax({
                                    url: webPath+"/notice/updateNoticeStatus",
                                    type: "POST",
                                    data:JSON.stringify(obj),
                                    contentType: 'application/json;charset=utf-8',
                                    success: function(data) {
                                        if (data.errorCode == "0") {
                                            initData();
                                            setTimeout(function () {
                                                layer.msg("修改成功");
                                            },800)

                                        }else layer.msg("修改失败")

                                    },
                                    error: function(xhr, type, errorThrown) {
                                        console.info( );
                                        layer.msg("失败  "+JSON.stringify(xhr.responseJSON)  + "  "+JSON.stringify(errorThrown))
                                    }
                                })//ajax



                            });

                        }
                    });
                });
            }

            var noticeTypes ;
            function getNoticeTypes() {
                $.ajax({
                    url: webPath+"/noticeType/getNoticeTypeList",
                    type: "POST",
					async:false,
                    contentType: 'application/json;charset=utf-8',
                    success: function(data) {
                        if (data.errorCode == "0") {
                            console.info("获取通知的类型成功");
                            noticeTypes = data.body.noticeTypes;
                            var notice_type_select = $("#notice-type-select");
                            var option = "";
                            for (var i = 0;i<noticeTypes.length; i++)
                                option +=  '<option value="'+ noticeTypes[i].id+'"> '+noticeTypes[i].typeName+' </option>' ;

                            notice_type_select.append(option)
                        }else  console.info("获取通知的类型失败 "+JSON.stringify(data ))

                    },
                    error: function(xhr, type, errorThrown) {
                        layer.msg("失败  "+xhr.responseJSON + "  "+errorThrown)
                    }
                })//ajax

            }

			$("#deleteNotices").click(function () {
				deleteNotices();
			});

			//删除通知
			function deleteNotices() {

				layui.use([ 'table','layer'] , function (){
					var table = layui.table;
					var layer = layui.layer;

					var checkStatus = table.checkStatus('dataTable');
					var data = checkStatus.data;
					if (data.length < 1) {
						layer.msg("请选择要操作的数据");
						return;
					}

					layer.confirm('您确定要删除吗?',{btn: ['确定', '取消'],title:"提示"}, function(){
						var ids = [];
						$.each(data,function (index,ele) {
							ids.push(ele.id);
						})
						var obj = {ids:ids};
						console.info(obj);
						$.ajax({
							data : JSON.stringify(obj),
							type:'post',
							contentType : 'application/json; charset=utf-8',
							dataType : 'json', //返回值的类型，不是必须的，且依据返回值类型而定。
							url:webPath+'/notice/deleteBatch',
							success:function(data){
								console.info(data);
								if (data.errorCode == "0") {
									layer.msg("成功删除");
									setTimeout(function () {initData();},300);

								}
								else layer.msg("删除失败");
							},
							error:function(data){
								layer.msg("网络出错");
							}
						});//ajax
					});

				})

			}

            //单击行勾选checkbox事件
            $(document).on("click",".layui-table-body table.layui-table tbody tr", function () {
                var index = $(this).attr('data-index');
                var tableBox = $(this).parents('.layui-table-box');
                //存在固定列
                if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length>0) {
                    tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
                } else {
                    tableDiv = tableBox.find(".layui-table-body.layui-table-main");
                }
                var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
                if (checkCell.length>0) {
                    checkCell.click();
                }
            });

            $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
                e.stopPropagation();
            });



        })

	</script>


</div>
</body>

</html>